import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import { Form, Input, Button, Toast, NavBar } from "antd-mobile";
import { EyeInvisibleOutline, EyeOutline } from "antd-mobile-icons";
import http from "../../utils/http";
import styles from "./index.module.css";

const Index = () => {
  const navigate = useNavigate();
  const [visible, setVisible] = useState(false);

  // 提交表单
  const onFinish = async (values) => {
    const res = await http.post("/api/login", values);
    const { code, message, data } = res.data;
    if (code === 200) {
      localStorage.setItem("userInfo", JSON.stringify(data.userInfo));
      localStorage.setItem("token", data.token);
      navigate("/");
    } else {
      Toast.show({
        icon: "fail",
        content: message,
      });
    }
  };

  return (
    <div className={styles.zhuce_box}>
      <NavBar
        backIcon={false}
        right={<span onClick={() => navigate("/register")}>注册</span>}
      >
        登陆
      </NavBar>

      <Form
        layout="horizontal"
        onFinish={onFinish}
        footer={
          <Button block type="submit" className={styles.zhuce_but} size="large">
            提交
          </Button>
        }
      >
        <Form.Item
          name="username"
          label="用户名"
          rules={[
            {
              required: true,
              message: "用户名格式输入不正确",
              pattern: /^1[3-9]\d{9}$/, 
            },
          ]}
        >
          <Input placeholder="请输入用户名：邮箱" />
        </Form.Item>
        <Form.Item
          name="password"
          label="密码"
          rules={[
            {
              required: true,
              message: "密码输入不能为空",
              pattern: /^\w{6,12}$/
            },
          ]}
          className={styles.password}
        >
          <Input
            placeholder="请输入密码: 大小写字母、数字、特殊符号"
            type={visible ? "text" : "password"}
          />
        </Form.Item>
        <div className={styles.eye}>
          {!visible ? (
            <EyeInvisibleOutline onClick={() => setVisible(true)} />
          ) : (
            <EyeOutline onClick={() => setVisible(false)} />
          )}
        </div>
      </Form>
    </div>
  );
};
export default Index;
